package com.zd.mole.site.mohurd.process;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.web.ProjectedPayload;
import org.springframework.stereotype.Component;

import com.zd.mole.process.ProcessHandler;
import com.zd.mole.site.mohurd.entity.Ot_achievement_info;
import com.zd.mole.site.mohurd.entity.Ot_procomplete_info;
import com.zd.mole.site.mohurd.entity.Ot_proreview_info;
import com.zd.mole.site.mohurd.repository.OtAchievementInfoRepository;
import com.zd.mole.site.mohurd.repository.OtCompanyInfoRepository;
import com.zd.mole.site.mohurd.repository.OtPersonInfoRepository;
import com.zd.mole.site.mohurd.service.SysDictService;
import com.zd.mole.task.TaskStatus;
import com.zd.mole.task.entity.Task;
import com.zd.mole.task.service.TaskService;
import com.zd.mole.utils.RegexUtils;

/**
 * 项目信息/施工图审查
 * 
 * @author ZhangDi
 * 
 */
@Component
@Transactional
public class MohurdDataserviceQueryProjectCensorInfoHandler implements ProcessHandler {

	private Logger log = LoggerFactory.getLogger(getClass());

	@PersistenceContext
	private EntityManager em;
	@Resource
	private OtCompanyInfoRepository otCompanyInfoRepository;
	@Resource
	private OtPersonInfoRepository otPersonInfoRepository;
	@Resource
	private OtAchievementInfoRepository otAchievementInfoRepository;
	@Resource
	private TaskService taskService;
	@Resource
	private SysDictService sysDictService;

	@Override
	public List<Task> handler(Task task, String text) {

		Ot_proreview_info p = new Ot_proreview_info();
		String id = task.getRequestUrl().replaceFirst("/dataservice/query/project/censorInfo/", "");
		p.setId(id);
		p.setProjectNo(task.getCode());

		p.setOrgReviewDisplay(RegexUtils.find("<td data-header=\"施工图审查机构名称\">" + INNER_HTML + "</td>", text));
		p.setOrgReviewCode(RegexUtils.find("<td data-header=\"施工图审查机构组织机构代码\">" + INNER_HTML + "</td>", text));

		p.setCertificateCode(RegexUtils.find("<td data-header=\"施工图审查合格书编号\">" + INNER_HTML + "</td>", text));
		p.setProCertificateCode(RegexUtils.find("<td data-header=\"省级施工图审查合格书编号\">" + INNER_HTML + "</td>", text));
		String reviewFinalDate = RegexUtils.find("<td colspan=\"3\" data-header=\"审查完成日期\">" + INNER_HTML + "</td>",
				text);
		try {
			p.setReviewFinalDate(new SimpleDateFormat("yyyy-MM-dd").parse(reviewFinalDate));
		} catch (ParseException e) {
			log.warn("日期转换失败 {}", e.getMessage());
		}
		p.setBuiltModel(RegexUtils.find("<td colspan=\"3\" data-header=\"建设规模\">" + INNER_HTML + "</td>", text));

		p.setCreate_by("1");
		p.setUpdate_by("1");
		p.setCreate_date(new Date());
		p.setUpdate_date(new Date());
		p.setDel_flag("0");

		String reviewUnitId = RegexUtils.find("<td data-header=\"涉及单位\">勘察单位</td>" + "\\s*<td data-header=\"企业名称\">"
				+ "\\s*<a href=\"/dataservice/query/comp/compDetail/(\\d+)\" target=\"_blank\">" + INNER_HTML + "</a>"
				+ "\\s*</td>", text);
		p.setReviewUnitName(reviewUnitId);
		if (!"".equals(reviewUnitId)) {
			p.setReviewUnitDisplay(
					RegexUtils.find("<td data-header=\"涉及单位\">勘察单位</td>" + "\\s*<td data-header=\"企业名称\">"
							+ "\\s*<a href=\"/dataservice/query/comp/compDetail/\\d+\" target=\"_blank\">" + INNER_HTML
							+ "</a>" + "\\s*</td>", text));
			addCompanyTask(task, reviewUnitId);
		} else {
			p.setReviewUnitDisplay(RegexUtils.find("<td data-header=\"涉及单位\">勘察单位</td>"
					+ "\\s*<td data-header=\"企业名称\">" + "\\s*" + INNER_HTML + "\\s*</td>", text));
		}
		String reviewUnit = RegexUtils.find("<td data-header=\"涉及单位\">勘察单位</td>" + INNER_HTML + "</tr>", text);
		p.setReviewUnitCode(RegexUtils.find("<td data-header=\"组织机构代码\">" + INNER_HTML + "</td>", reviewUnit));

		String designUnitId = RegexUtils.find("<td data-header=\"涉及单位\">设计单位</td>" + "\\s*<td data-header=\"企业名称\">"
				+ "\\s*<a href=\"/dataservice/query/comp/compDetail/(\\d+)\" target=\"_blank\">" + INNER_HTML + "</a>"
				+ "\\s*</td>", text);
		p.setDesignUnitName(designUnitId);
		if (!"".equals(designUnitId)) {
			p.setDesignUnitDisplay(
					RegexUtils.find("<td data-header=\"涉及单位\">设计单位</td>" + "\\s*<td data-header=\"企业名称\">"
							+ "\\s*<a href=\"/dataservice/query/comp/compDetail/\\d+\" target=\"_blank\">" + INNER_HTML
							+ "</a>" + "\\s*</td>", text));
			addCompanyTask(task, designUnitId);
		} else {
			p.setDesignUnitDisplay(RegexUtils.find("<td data-header=\"涉及单位\">设计单位</td>"
					+ "\\s*<td data-header=\"企业名称\">" + "\\s*" + INNER_HTML + "\\s*</td>", text));
		}
		String designUnit = RegexUtils.find("<td data-header=\"涉及单位\">设计单位</td>" + INNER_HTML + "</tr>", text);
		p.setDesignUnitCode(RegexUtils.find("<td data-header=\"组织机构代码\">" + INNER_HTML + "</td>", designUnit));

		em.merge(p);

		String personText = RegexUtils.find(
				"<label style=\"color: #015293; font-size: 18px; line-height: 29px;\">从业人员信息</label>"
						+ "\\s*<table width=\"100%\" class=\"pro_table_box pro_table_borderright\">" + "</table>",
				text);

		RegexUtils.findAll("<tr>" + INNER_HTML + "</tr>", personText).forEach(tr -> {
			
			String thatTimeCompany = RegexUtils.find("<td data-header=\"所在企业\">" + INNER_HTML + "</td>", tr);
			String majorName = RegexUtils.find("<td data-header=\"专业名称\">" + INNER_HTML + "</td>", tr);
			String serveRole  = RegexUtils.find("<td data-header=\"担任角色\">" + INNER_HTML + "</td>", tr);
			
			String custId = RegexUtils.find("<td data-header=\"姓名\">"
					+ "\\s*<a href=\"/dataservice/query/staff/staffDetail/(\\d+)\" target=\"_blank\">" + INNER_HTML
					+ "</a>" + "\\s*</td>", tr);
			String personName = "";
			if (!"".equals(custId)) {
				personName = RegexUtils.find("<td data-header=\"姓名\">"
						+ "\\s*<a href=\"/dataservice/query/staff/staffDetail/\\d+\" target=\"_blank\">" + INNER_HTML
						+ "</a>" + "\\s*</td>", tr);
				// addPersonTask(task, personId);
			} else {
				personName = RegexUtils.find("<td data-header=\"姓名\">\\s*" + INNER_HTML + "\\s*</td>", tr);
			}

			String cardNo = RegexUtils.find("<td data-header=\"证件号码\">" + INNER_HTML + "</td>", tr);
			String registerType = RegexUtils.find("<td data-header=\"注册类型及等级\">" + INNER_HTML + "</td>", tr);
			String practiceNo = RegexUtils.find("<td data-header=\"执业印章号\">" + INNER_HTML + "</td>", tr);

			List<Ot_achievement_info> ais = em
					.createQuery("from Ot_achievement_info where ProjectNo = :ProjectNo and custId = :custId")
					.setParameter("ProjectNo", task.getCode()).setParameter("custId", custId).getResultList();
			Ot_achievement_info ai = new Ot_achievement_info();
			if (ais.size() > 0) {
				ai = ais.get(0);
			} else {
				ai.setCustid(custId);
				ai.setProjectNo(task.getCode());
				
				ai.setProjectName(RegexUtils.find("<td colspan=\"3\" data-header=\"项目名称\">" + INNER_HTML + "</td>", personText));
				String projectArea2 = RegexUtils.find("<td data-header=\"项目属地\">" + INNER_HTML + "</td>", personText);
				String projectArea = RegexUtils.find("^([\u4e00-\u9fa5]+)-.*", projectArea2);
				projectArea = sysDictService.findOrSaveByTypeLabel("oLife_ComAreaScope", projectArea, "企业注册属地");
				ai.setProjectArea(projectArea);
				ai.setProjectArea2(projectArea2);
				String projectType = RegexUtils.find("<td data-header=\"项目分类\">" + CN_REGEX + "</td>", tr);
				projectType = sysDictService.findOrSaveByTypeLabel("oLife_ProjectType", projectType, "项目类别");
				ai.setProjectType(projectType);
				ai.setDevelopmentDw(RegexUtils.find("<td data-header=\"建设单位\">" + CN_REGEX + "</td>", tr));
				ai.setThatTimeCompany(thatTimeCompany);
				ai.setMajorName(majorName);
				ai.setPersonName(personName);
				ai.setCardNo(cardNo);
				ai.setRegisterType(registerType);
				ai.setPracticeNo(practiceNo);
			}
			ai.setServeRole(serveRole);
			Ot_achievement_info a = new Ot_achievement_info();
			if (ais.size() > 0) {
				em.merge(ai);
			} else {
				ai.setId("u" + UUID.randomUUID().toString());
				em.persist(ai);
			}

		});

		return null;
	}

	private void addCompanyTask(Task task, String companyId) {
		if (!"".equals(companyId)) {
			if (!otCompanyInfoRepository.existsById(companyId)) {
				Task nt = new Task();
				nt.setCode(companyId);
				nt.setHostUrl(task.getHostUrl());
				nt.setRequestUrl("/dataservice/query/comp/compDetail/" + companyId);
				nt.setProcessHandlerClassName("MohurdDataserviceQueryCompCompDetailHandler");
				nt.setStatus(TaskStatus.Ready);
				taskService.save(nt);
			}
		}
	}

	private void addPersonTask(Task task, String personId) {
		if (!"".equals(personId)) {
			if (!otPersonInfoRepository.existsById(personId)) {
				Task nt = new Task();
				nt.setCode(personId);
				nt.setHostUrl(task.getHostUrl());
				nt.setRequestUrl("/dataservice/query/staff/staffDetail/" + personId);
				nt.setProcessHandlerClassName("MohurdDataserviceQueryStaffstaffDetailHandler");
				nt.setStatus(TaskStatus.Ready);
				taskService.save(nt);
			}
		}
	}

}
